package org.sandbox3.web;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.sandbox3.domain.bank.Account;
import org.sandbox3.domain.bank.TransferForm;
import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RooWebScaffold(path = "transferforms", formBackingObject = TransferForm.class)
@RequestMapping("/transferforms")
@Controller
public class TransferFormController {
	
	@RequestMapping(method = RequestMethod.POST)
    public String create(@Valid TransferForm transferForm, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            uiModel.addAttribute("transferForm", transferForm);
            return "transferforms/create";
        }
        uiModel.asMap().clear();
        Account fromAccount = Account.findAccount(transferForm.getFromAccountId());
        Account toAccount = Account.findAccount(transferForm.getToAccountId());
        fromAccount.transfer(toAccount, transferForm.getAmount());
        return "redirect:/accounts/";
    }
}
